package method

import (
	"image"
	"image/color"
	"image/draw"
	"image/png"
	"io"
	"log"
	"os"

	"github.com/golang/freetype"
	"github.com/golang/freetype/truetype"
	"github.com/google/uuid"
)

func PptImg(x, y int, text string) (string, error) {

	// Create a new image with white background
	img := image.NewRGBA(image.Rect(0, 0, x, y))
	white := color.RGBA{255, 255, 255, 255}
	draw.Draw(img, img.Bounds(), &image.Uniform{white}, image.Point{}, draw.Src)

	// Open the font file
	fontFile, err := os.Open("./font/dyh.ttf") // Replace with the path to your font file
	if err != nil {
		return "", err
	}
	defer fontFile.Close()

	// Read the font file
	fontBytes, err := io.ReadAll(fontFile)
	if err != nil {
		return "", err
	}
	f, err := truetype.Parse(fontBytes)
	if err != nil {
		return "", err
	}

	// Create a new freetype context
	ctx := freetype.NewContext()
	ctx.SetDPI(72)
	ctx.SetFont(f)
	ctx.SetFontSize(40)
	ctx.SetClip(img.Bounds())
	ctx.SetDst(img)
	ctx.SetSrc(image.Black)

	// Measure the width of the text
	width := (len(text) / 3 / 2) * 40
	// Calculate the position to center the text horizontally
	textX := x/2 - width + 10
	// Calculate the position to center the text vertically
	textY := (y + int(ctx.PointToFixed(40)>>6)) / 2
	log.Println(textX, textY, width, len(text))
	// Draw the text on the image
	pt := freetype.Pt(textX, textY)
	_, err = ctx.DrawString(text, pt)
	if err != nil {
		return "", err
	}

	// Generate a unique filename for the output image
	output := "./img/" + uuid.New().String() + ".png"

	// Create the output file
	outFile, err := os.Create(output)
	if err != nil {
		return "", err
	}
	defer outFile.Close()

	// Encode the image as PNG and save it to the output file
	err = png.Encode(outFile, img)
	if err != nil {
		return "", err
	}

	return output, nil
}
